package com.zsinfo.guoss.supplier.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.netcenter.Event.UpLoadResponse;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.bean.NewProductBean;
import com.example.netcenter.bean.ResultsData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanzhenjie.permission.AndPermission;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.base.BaseActivity;
import com.zsinfo.guoss.supplier.customize.ActionSheetDialog;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by lixl on 2018/12/6.
 * <p>
 * desc:添加 我的上新
 */
public class NewProductAddActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_new_produce_name;
    private ImageView iv1, iv2, iv3;
    private EditText et_new_produce_place;
    private EditText et_new_produce_packaging;
    private EditText et_new_produce_size;
    private EditText et_new_produce_price;
    private TextView tv_jian, tv_jin, tv_ge;
    private EditText et_remark;
    private Button btn_add;

    private String imagePath; //默认图片
    private String imgPath1 = "", imgPath2 = "", imgPath3 = "";
    private int chooseImg = 1; //当前选中的图片：1，2，3
    private String priceType = "件"; //1 按件，2 按斤，3 按个

    @Override
    protected int getContentLayoutRes() {
        return R.layout.activity_new_product_add;
    }

    @Override
    protected void initView() {
        setTitle("上新");
        setBackAndLeftTitle("").setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        et_new_produce_name = findViewById(R.id.et_new_produce_name);
        iv1 = findViewById(R.id.iv1);
        iv2 = findViewById(R.id.iv2);
        iv3 = findViewById(R.id.iv3);
        et_new_produce_place = findViewById(R.id.et_new_produce_place);
        et_new_produce_packaging = findViewById(R.id.et_new_produce_packaging);
        et_new_produce_size = findViewById(R.id.et_new_produce_size);
        et_new_produce_price = findViewById(R.id.et_new_produce_price);
        tv_jian = findViewById(R.id.tv_jian);
        tv_jin = findViewById(R.id.tv_jin);
        tv_ge = findViewById(R.id.tv_ge);
        et_remark = findViewById(R.id.et_remark);
        btn_add = findViewById(R.id.btn_add);

        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv3.setOnClickListener(this);
        tv_jian.setOnClickListener(this);
        tv_jin.setOnClickListener(this);
        tv_ge.setOnClickListener(this);
        btn_add.setOnClickListener(this);
    }

    @Override
    protected void initNetData() {

    }

    @Override
    protected void customDestroy() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv1:
                chooseImg = 1;
                choosePictureDialog();
                break;
            case R.id.iv2:
                chooseImg = 2;
                choosePictureDialog();
                break;
            case R.id.iv3:
                chooseImg = 3;
                choosePictureDialog();
                break;
            case R.id.tv_jian:
                showToast("金额需精确到两位小数");
                priceType = "件";
                changePriceUI(priceType);
                break;
            case R.id.tv_jin:
                showToast("金额需精确到两位小数");
                priceType = "斤";
                changePriceUI(priceType);
                break;
            case R.id.tv_ge:
                showToast("金额需精确到两位小数");
                priceType = "个";
                changePriceUI(priceType);
                break;
            case R.id.btn_add:
                submitBeforeJudgment();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 101) {
                if (!TextUtils.isEmpty(imagePath)) {
                    //逻辑处理
                    picturedDeal();
                } else {
                    showToast("找不到图片文件");
                }
            } else if (requestCode == 102) {
                if (data != null) {
                    Uri uri = data.getData();
                    Cursor cursor = getContentResolver()
                            .query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    imagePath = cursor.getString(1);
                    cursor.close();

                    picturedDeal();
                } else {
                    showToast("网络链接异常，清检查网络后再试");
                }
            } else {
                showToast("没有获取到您所选择的图片");
            }
        }
    }

    /**
     * 选择拍照，图库
     */
    private void choosePictureDialog(){
        new ActionSheetDialog(NewProductAddActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("照相机", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (AndPermission.hasPermission(NewProductAddActivity.this, Manifest.permission.CAMERA)) {
                                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                        File file = new File(
                                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(),
                                                System.currentTimeMillis() + ".png");
                                        Uri photoURI = FileProvider.getUriForFile(NewProductAddActivity.this, NewProductAddActivity.this.getApplicationContext().getPackageName() + ".Fileprovider",
                                                file);
                                        Intent intent = new Intent();
                                        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                                        imagePath = file.getAbsolutePath();
                                        startActivityForResult(intent,101);
                                    }
                                } else {
                                    AndPermission.with(NewProductAddActivity.this)
                                            .permission(Manifest.permission.CAMERA)
                                            .requestCode(10000)
                                            .send();
                                }
                            }
                        })
                .addSheetItem("本地相册", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (AndPermission.hasPermission(NewProductAddActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK,
                                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    intent.setDataAndType(
                                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                            "image/*");
                                    startActivityForResult(intent, 102);
                                } else {
                                    AndPermission.with(NewProductAddActivity.this)
                                            .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                            .requestCode(20000)
                                            .send();
                                }
                            }
                        }).show();
    }

    /**
     * 图片处理：包括添加图片，图片退换
     */
    private void picturedDeal(){
        if (chooseImg == 1){
            //显示第一张图片
            imgPath1 = imagePath;
            Glide.with(NewProductAddActivity.this).load(imgPath1).placeholder(R.mipmap.no_data).error(R.mipmap.no_data).crossFade().into(iv1);
        } else if (chooseImg == 2){
            //显示第二张图片
            imgPath2 = imagePath;
            Glide.with(NewProductAddActivity.this).load(imgPath2).placeholder(R.mipmap.no_data).error(R.mipmap.no_data).crossFade().into(iv2);
        } else if (chooseImg == 3){
            //显示第三张图片
            imgPath3 = imagePath;
            Glide.with(NewProductAddActivity.this).load(imgPath3).placeholder(R.mipmap.no_data).error(R.mipmap.no_data).crossFade().into(iv3);
        }
    }

    /**
     * 修改 新品价格 选中的状态
     */
    private void changePriceUI(String type){
        //全部改成 未选中状态
        tv_jian.setTextColor(getResources().getColor(R.color.gray));
        tv_jian.setBackgroundResource(R.drawable.shape_arc_gray_gray_5);
        tv_jin.setTextColor(getResources().getColor(R.color.gray));
        tv_jin.setBackgroundResource(R.drawable.shape_arc_gray_gray_5);
        tv_ge.setTextColor(getResources().getColor(R.color.gray));
        tv_ge.setBackgroundResource(R.drawable.shape_arc_gray_gray_5);
        //根据priceType 更换选中状态
        if (type.equals("件")){
            tv_jian.setTextColor(getResources().getColor(R.color.main_color));
            tv_jian.setBackgroundResource(R.drawable.shape_arc_orange_orange_5);
        } else if (type.equals("斤")){
            tv_jin.setTextColor(getResources().getColor(R.color.main_color));
            tv_jin.setBackgroundResource(R.drawable.shape_arc_orange_orange_5);
        } else if (type.equals("个")){
            tv_ge.setTextColor(getResources().getColor(R.color.main_color));
            tv_ge.setBackgroundResource(R.drawable.shape_arc_orange_orange_5);
        }

    }

    /**
     * 提交上新，判断所有（必填）
     */
    private void submitBeforeJudgment(){
        String productName = et_new_produce_name.getText().toString().trim();
        if (TextUtils.isEmpty(productName)){
            showToast("请输入新品名称");
            return;
        }
        if (TextUtils.isEmpty(imgPath1) || TextUtils.isEmpty(imgPath2) || TextUtils.isEmpty(imgPath3)){
            showToast("请根据要求上传新品图片");
            return;
        }
        String productPlace = et_new_produce_place.getText().toString().trim();
        if (TextUtils.isEmpty(productPlace)){
            showToast("请输入供应新品的产地");
            return;
        }
        String productPackageing = et_new_produce_packaging.getText().toString().trim();
        if (TextUtils.isEmpty(productPackageing)){
            showToast("请输入新品包装类型");
            return;
        }
        String productSize = et_new_produce_size.getText().toString().trim();
        if (TextUtils.isEmpty(productSize)){
            showToast("请输入新品规格");
            return;
        }
        String productPrice = et_new_produce_price.getText().toString().trim();
        if (TextUtils.isEmpty(productPrice)){
            showToast("请输入新品价格");
            return;
        }
        String productRemark = et_remark.getText().toString().trim();
        if (TextUtils.isEmpty(productRemark)){
            showToast("请填写备注");
            return;
        }

        Log.e("新品添加", "名称------"+ productName);
        Log.e("新品添加", "产地------"+ productPlace);
        Log.e("新品添加", "包装类型------"+ productPackageing);
        Log.e("新品添加", "规格------"+ productSize);
        Log.e("新品添加", "价格------"+ productPrice);
        Log.e("新品添加", "价格类型------type = "+ priceType);
        Log.e("新品添加", "备注------"+ productRemark);
        Log.e("新品添加", "图片1------"+ imgPath1);
        Log.e("新品添加", "图片2------"+ imgPath2);
        Log.e("新品添加", "图片3------"+ imgPath3);

        dialog = ProgressDialog.show(this, "", "努力加载中...");
        List<String> imagePaths = new ArrayList<>();
        imagePaths.add(imgPath1);
        imagePaths.add(imgPath2);
        imagePaths.add(imgPath3);
        RetrofitBuilder.UpLoadImage(imagePaths,
                SharedPreferencesUtil.getID(),
                productName,
                productPlace,
                productPackageing,
                productSize,
                priceType,
                productPrice,
                productRemark,
                new UpLoadResponse() {
                    @Override
                    public void UpLoad(String s) {
                        Log.e("lixl", s);
                        Gson gson = new Gson();
                        Type lt= new TypeToken<ResultsData<NewProductBean>>(){}.getType();
                        final ResultsData<NewProductBean> resultsData = gson.fromJson(s, lt);
                        if (resultsData.getStatusCode().equals("100000")){
                            //主线程
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("添加成功");
                                    //将新添加的数据，返回给上一个界面
                                    NewProductBean newProductBean = resultsData.getData();
                                    Intent intent = new Intent(NewProductAddActivity.this, NewProductActivity.class);
                                    intent.putExtra("newProductBean", newProductBean);
                                    setResult(2, intent);
                                    finish();
                                }
                            });
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                        });
                    }

                    @Override
                    public void UpLoadFail(Call call, IOException e) {
                        Log.e("lixl", e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                        });
                    }
                });
    }
}
